package com.app.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xiaoyu.fang
 * @date 2020/1/8 16:13
 */
@Slf4j
@Component
public class RabbitSender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    /**
     * 发送延迟消息
     *
     * @param messageContent
     * @param exchange
     * @param routerKey
     * @param delayTimes
     */
    public void sendDelayMsg(Object messageContent, String exchange, String routerKey, final long delayTimes) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String messageJson = JSON.toJSONString(messageContent);
            log.info("{} ============ 延迟{}毫秒写入消息队列：{}，消息内容：{}", format.format(new Date()), delayTimes, routerKey, messageJson);
            rabbitTemplate.convertAndSend(exchange, routerKey, messageJson, message -> {
                message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
                return message;
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("未找到队列消息：{}，所属的交换机", exchange);
        }
    }

}
